//  Parameter details refer to:https://support.huaweicloud.com/api-rds/rds_01_0002.html
resource "huaweicloud_rds_instance" "rds" {
  count             = var.is_rds_creat ? 1 : 0
  availability_zone = var.db_availability_zone
  ha_replication_mode = var.replication_mode
  charging_mode     = var.charging_mode
  period_unit       = var.period_unit
  period            = var.period
  name              = var.name_suffix != null ? format("%s-%s", var.db_instance_name, var.name_suffix) : var.db_instance_name
  time_zone         = var.time_zone
  flavor            = var.flavor
  vpc_id            = var.vpc_id
  subnet_id         = var.subnet_id
  security_group_id = var.security_group_id
  param_group_id    = var.param_group_id
  
  db {
    type     = var.db_engines
    version  = var.db_version
    password = var.db_password
    port     = var.db_port
  }
  volume {
    type               = var.db_instance_storage_type
    size               = var.db_allocated_storage
    disk_encryption_id = var.disk_encryption_id
  }

  backup_strategy {
    keep_days  = var.keep_days
    start_time = var.start_time
  }
  
  tags = merge(
    { "Name" = var.name_suffix != null ? format("%s-%s", var.db_instance_name, var.name_suffix) : var.db_instance_name},
    var.rds_tags)
}

//  Manages RDS Mysql database resource within HuaweiCloud.
resource "huaweicloud_rds_database" "mysql" {
  count         = var.mysql_configuration != null ? length(var.mysql_configuration) : 0
  instance_id   = huaweicloud_rds_instance.rds[0].id
  name          = lookup(element(var.mysql_configuration, count.index), "name")
  character_set = lookup(element(var.mysql_configuration, count.index), "character_set")
}
